package com.esp.studentManagementSystem.controller;

import com.esp.studentManagementSystem.pojo.po.entity.Student;
import com.esp.studentManagementSystem.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    @GetMapping("/students")
    public List<Student> findAll(){
        return studentRepository.findAll();
    }

    @GetMapping("/students/{id}")
    public Optional<Student> findById(@PathVariable Long id){
        Optional<Student> student = studentRepository.findById(id);
        System.out.println(student.isEmpty());
        if (student.isEmpty()){
            System.out.println("Student not found");
            throw new RuntimeException("Student not found");
        }
        return student;
    }

    @PostMapping("/students")
    @PreAuthorize("hasAuthority('student:add')")
    public Student save(@RequestBody Student student){
        return student;
    }

    @PutMapping("/students/{id}")
    public Student update(@PathVariable Long id, @RequestBody Student student){
        Student student1 = studentRepository.findById(id).get();
        student1.setName(student.getName());
        student1.setAge(student.getAge());
        student1.setGender(student.getGender());
        student1.setGrade(student.getGrade());
        return studentRepository.save(student1);
    }

    @DeleteMapping("/students/{id}")
    public Student delete(@PathVariable Long id){
        Student student = studentRepository.findById(id).get();
        studentRepository.delete(student);
        return student;
    }
}
